﻿using System.IO;
using System.Runtime.InteropServices;

namespace DimsMapper.Modules
{
    public class DBFile
    {
        BinaryReader stream;
        string pathName;

        public DBFile(string _pathName, BinaryReader _stream) 
        {
            pathName = _pathName;
            stream = _stream;
        }

        /// <summary>
        /// Конвертирует LittleEndian значение в BigEndian и обратно.
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        private int ReverseDWValue(int value)
        {
            if (value == 0 || value == -1) return value;

            return (value << 24) | (value & 0xFF00) << 8 | (value & 0xFF0000) >> 8 | (value >> 24) & 0xFF; ;
        }

        private ushort ReverseWValue(ushort value)
        {
            if (value == 0 || value == 0xFFFF) return value;

            return (ushort)((value & 0xFF00) >> 8 | (value & 0xFF) << 8); ;
        }

        public byte ReadByte()
        {
            return stream.ReadByte();
        }

        public ushort ReadShort()
        {
            ushort value = stream.ReadUInt16();
            return ReverseWValue(value);
        }

        public int ReadInt32()
        {
            return stream.ReadInt32();
        }

        public int ReadInt()
        {
            int value = ReadInt32();
            return ReverseDWValue(value);
        }

        public byte[] ReadBytes(int bytes)
        {
            return stream.ReadBytes(bytes);
        }

        public void SkipBytes(int bytes)
        {
            stream.BaseStream.Seek(bytes, SeekOrigin.Current);
        }

        public long Position()
        {
            return stream.BaseStream.Position;
        }

        public long Size()
        {
            return stream.BaseStream.Length;
        }

        public void Close()
        {
            stream.Close();
        }

        public override string ToString()
        {
            return pathName;
        }

        ///<summary>
        /// Преобразовывает массив в структуру
        ///</summary>
        //static object ConvertBytesToStruct(ref int[] data, System.Type strcType)
        //{
        //    GCHandle mGC = GCHandle.Alloc(data, GCHandleType.Pinned);
        //    object obj = Marshal.PtrToStructure(mGC.AddrOfPinnedObject(), strcType);
        //    mGC.Free();
        //    return obj;
        //}

        ///<summary>
        /// Преобразовывает структуру в массив
        ///</summary>
        //static void ConvertStructToBytes(ref byte[] bytes, object structure)
        //{
        //    System.IntPtr ptr = Marshal.AllocHGlobal(bytes.Length);
        //    Marshal.StructureToPtr(structure, ptr, false);
        //    Marshal.Copy(ptr, bytes, 0, bytes.Length);
        //    Marshal.FreeHGlobal(ptr);
        //}
    }
}
